
<template>
  <el-dialog v-dialogDrag :visible.sync="currentDialogVisible" :top="common.getDialogTop()" title="SQL数据集配置" class="dialog-container" width="1200px" append-to-body>
    <div class="panel-body">
      <div class="panel-left">
        <div class="search-box">
          <el-input v-model="formData.searchKey" placeholder="表名查询" class="search-key"></el-input>
          <el-button><i class="el-icon-yrt-chaxun"></i></el-button>
        </div>
        <div class="left-content">
          <template v-for="(item, index) in tableList">
            <a :key="index" class="item" @dblclick="tableDbclick(item)">{{ item.name }}</a>
            <br :key="index+'br'" />
          </template>
        </div>
      </div>
      <div class="panel-right">
        <el-form ref="form" :model="formData" label-width="100px">
          <el-form-item label="数据集名称：">
            <el-input v-model="formData.name" class="w-100pc"></el-input>
          </el-form-item>
          <el-form-item label="SQL：">
            <el-input v-model="formData.sql" class="w-100pc" type="textarea" rows="6" placeholder="SQL支持表达式，格式为：${表达式...}"></el-input>
          </el-form-item>
        </el-form>
        <div class="param-box">
          <div class="param-title">
            <span class="title">查询参数</span>
            <el-button type="text" @click="paramAdd"> <i class="el-icon-yrt-yuanquanjiahao margin-left-10"></i> 添加参数</el-button>
          </div>
          <el-table :data="parameters" style="width: 100%" max-height="300px">
            <el-table-column prop="name" label="参数名">
              <template slot-scope="{row, column}">
                <el-input v-model="row.name" placeholder="请输入参数名"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="date" label="数据类型" width="150">
              <template slot-scope="{row, column}">
                <el-select v-model="row.type" placeholder="请选择数据类型">
                  <el-option v-for="(item, index) in paramTypeList" :key="index" :label="item" :value="item">
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="address" label="默认值" width="150">
              <template slot-scope="{row, column}">
                <el-input v-model="row.defaultValue" placeholder="请输入默认值"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="date" label="操作" width="80">
              <template slot-scope="{row, column}">
                <el-button type="text" size="small" @click="paramDelete(row)">
                  <span>删除</span>
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="currentDialogVisible = false">取 消</el-button>
      <el-button :loading="isLoading" type="primary" icon="el-icon-yrt-icon2" @click="preview">预览数据</el-button>
      <el-button :loading="isLoading" type="primary" icon="el-icon-yrt-baocun" @click="save">确定</el-button>
    </span>

    <!--数据预览对话框-->
    <preview-data-dialog ref="previewDataDialog" :visible.sync="showPreviewDataDialog" :designer="designer" :datasource="currentDatasource" :dataset="dataset">
    </preview-data-dialog>

  </el-dialog>
</template>

<script>
import previewDataDialog from "./previewDataDialog";

export default {
  components: {
    previewDataDialog
  },
  props: {
    designer: {
      type: Object,
      default: () => {
        return {};
      }
    },
    // 当前编辑的数据
    currentDatasource: {
      type: Object,
      default: () => {
        return {};
      }
    },
    visible: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      isLoading: false,
      dataset: null,
      formData: {
        searchKey: null,
        name: null,
        sql: null
      },
      tableList: [],
      paramTypeList: ["String", "Integer", "Float", "Boolean", "Date", "List"], // 数据类型
      parameters: [], // 参数集合
      // 显示预览数据对话框
      showPreviewDataDialog: false
    };
  },
  computed: {
    // 显示窗口
    currentDialogVisible: {
      get: function () {
        return this.visible;
      },
      set: function (val) {
        this.$emit("update:visible", val);
      }
    }
  },
  watch: {},
  methods: {
    paramAdd () {
      this.parameters.push({
        type: "String"
      });
    },
    paramDelete (row) {
      const index = this.parameters.findIndex(item => item === row);
      this.parameters.splice(index, 1);
    },
    // 更新数据
    updateData () {
      const { context } = this.designer;
      const datasources = context.reportDef.datasources;

      if (!this.formData.name) {
        this.$message.error("数据集名称不能为空");
        return false;
      }
      if (!this.formData.sql) {
        this.$message.error("sql不能为空");
        return false;
      }
      const datasource = datasources.find(item => item.name === this.currentDatasource.name);
      if (!datasource.datasets) datasource.datasets = [];
      const dataset = datasource.datasets.find(item => item.name === this.formData.name);
      if (dataset) {
        this.currentDatasource = datasource;
        this.dataset = dataset;
      }

      this.dataset.sql = this.formData.sql;
      this.dataset.parameters = this.parameters;
      if (!this.dataset.name) {
        this.dataset.name = this.formData.name;
        this.$set(datasource.datasets, datasource.datasets.length, this.dataset);
      } else {
        this.dataset.name = this.formData.name;
      }
      return datasource;
    },
    preview () {
      const datasource = this.updateData();
      if (!datasource) return;
      this.showPreviewDataDialog = true;
    },
    save () {
      const datasource = this.updateData();
      if (!datasource) return;

      // 初始化字段
      this.buildFileds(datasource);

      this.$emit("on-datasource-success");
      this.currentDialogVisible = false;
      this.$message.success("数据源设置成功");
    },
    // 初始化
    init (dataset) {
      this.$nextTick(() => {
        this.buildDatabaseTables();
      });
      if (dataset) {
        this.dataset = dataset;
        this.formData.name = dataset.name;
        this.formData.sql = dataset.sql;
        this.parameters = [];
        for (const item of dataset.parameters) {
          this.$set(this.parameters, this.parameters.length, item);
        }
      } else {
        this.dataset = {
          parameters: []
        };

        this.formData.name = null;
        this.formData.sql = null;
        this.parameters = [];
      }
    },
    // 构建字段集合
    buildFileds (datasource) {
      const { dataset } = this;

      dataset.fields = [];
      const url = "/datasource/buildFields";
      let data = {
        name: datasource.name,
        sql: dataset.sql,
        parameters: JSON.stringify(dataset.parameters),
        type: datasource.type,
        username: datasource.username
      };
      if (datasource.type === "jdbc") {
        data = Object.assign(data, {
          password: datasource.password,
          driver: datasource.driver,
          url: datasource.url
        });
      }
      this.designer.ajax(url, data, res => {
        if (res.code === 200) {
          let index = 0;
          for (const field of res.data) {
            this.$set(dataset.fields, index, field);
            index++;
          }
        } else {
          this.$message.error("服务端错误：" + res.msg + "");
        }
        this.$emit("on-datasource-success");
      });
    },
    // 获取表列表
    buildDatabaseTables () {
      const type = this.currentDatasource.type;
      const params = { type };
      if (type === "jdbc") {
        params.username = this.currentDatasource.username;
        params.password = this.currentDatasource.password;
        params.driver = this.currentDatasource.driver;
        params.url = this.currentDatasource.url;
      } else if (type === "buildin") {
        params.name = this.currentDatasource.name;
      }
      const url = "/datasource/buildDatabaseTables";
      this.designer.ajax(url, params, res => {
        if (res.code === 200) {
          this.tableList = res.data;
        }
      });
    },
    // 选择表
    tableDbclick (table) {
      this.formData.sql = "select * from " + table.name + "";
    }
  }
};
</script>

<style lang="scss" scoped>
.dialog-container {
  .search-box {
    .search-key {
      width: 200px;
    }
  }
  .panel-body {
    display: flex;
    height: 100%;
    width: 100%;
  }
  .panel-left {
    height: 100%;
    width: 280px;
  }
  .panel-right {
    height: 100%;
    flex: 1;
  }
  .left-content {
    max-height: 550px;
    overflow-y: auto;
    -webkit-touch-callout: none; /*系统默认菜单被禁用*/
    -webkit-user-select: none; /*webkit浏览器*/
    -khtml-user-select: none; /*早期浏览器*/
    -moz-user-select: none; /*火狐*/
    -ms-user-select: none; /*IE10*/
    user-select: none;
    .item {
      display: inline-block;
      padding: 5px 10px 2px;
      color: dodgerblue;
      cursor: pointer;
      text-decoration: none;
      &:hover {
        border-bottom: 1px solid dodgerblue;
      }
      &::after {
        content: " ";
        display: block;
        clear: both;
      }
    }
  }
  .panel-right {
    .param-box {
      param-title {
        padding: 5px 10px;
      }
    }
  }
}
</style>
